package com.example.harmonet.slice;

import com.example.harmonet.ResourceTable;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;

import ohos.aafwk.content.Operation;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.bundle.ElementName;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.rpc.IRemoteObject;
import ohos.sensor.agent.CategoryMotionAgent;
import ohos.sensor.bean.CategoryMotion;
import ohos.sensor.data.CategoryMotionData;
import ohos.sensor.listener.ICategoryMotionDataCallback;

import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice {
    private static final long INTERVAL = 20000000L;

    private CategoryMotionAgent categoryMotionAgent = new CategoryMotionAgent();

    private ICategoryMotionDataCallback totalDataCallback, gyroDataCallback;

    private CategoryMotion totalMotionSensor, gyroMotionSensor;

    private HiLogLabel label = new HiLogLabel(ohos.hiviewdfx.HiLog.LOG_APP, 0x00201, "test");

    private Measurement accelMeasurements;
    private Measurement gyroMeasurements;

    private Classifier classifier;

    private UdpClient udpClient = new UdpClient();

    private final String []classes = {"RESTING", "STANDING", "WALKING", "FALLING", "WALKING UPSTAIRS", "WALKING DOWNSTAIRS", "STANDING UP", "SITTING"};

    private String result = "";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        HiLog.warn(label, "this is a test");

        //Initializing Measurements (all set to 0)
        accelMeasurements = new Measurement(false);
        gyroMeasurements = new Measurement(false);

        classifier = new Classifier(this);
        classifier.init();

        // 创建传感器回调对象
        totalDataCallback = new ICategoryMotionDataCallback() {

            @Override
            public void onSensorDataModified(CategoryMotionData categoryMotionData) {
                // HiLog.warn(label, ((Float)categoryMotionData.getValues()[0]).toString());
                accelMeasurements.insert(categoryMotionData.getValues()[0] / 9.80665, categoryMotionData.getValues()[0] / 9.80665, categoryMotionData.getValues()[0] / 9.80665); //We want to save the data in g units
                if (accelMeasurements.isFull() && gyroMeasurements.isFull()) {
                    HiLog.warn(label, "classify");
                    performClassification();
                    accelMeasurements.rearrangeHalfBack();
                    gyroMeasurements.rearrangeHalfBack();
                }
            }

            @Override
            public void onAccuracyDataModified(CategoryMotion categoryMotion, int i) {

            }

            @Override
            public void onCommandCompleted(CategoryMotion categoryMotion) {

            }
        };

        // 创建传感器回调对象。
        gyroDataCallback = new ICategoryMotionDataCallback() {

            @Override
            public void onSensorDataModified(CategoryMotionData categoryMotionData) {
                gyroMeasurements.insert(categoryMotionData.getValues()[0], categoryMotionData.getValues()[1], categoryMotionData.getValues()[2]);
                if (accelMeasurements.isFull() && gyroMeasurements.isFull()) {
                    HiLog.warn(label, "classify");
                    performClassification();
                    accelMeasurements.rearrangeHalfBack();
                    gyroMeasurements.rearrangeHalfBack();
                }
            }

            @Override
            public void onAccuracyDataModified(CategoryMotion categoryMotion, int i) {

            }

            @Override
            public void onCommandCompleted(CategoryMotion categoryMotion) {

            }
        };

        // 线性加速度（含重力加速度）
        totalMotionSensor = categoryMotionAgent.getSingleSensor(
                CategoryMotion.SENSOR_TYPE_ACCELEROMETER);
        if (totalMotionSensor != null) {
            categoryMotionAgent.setSensorDataCallback(
                    totalDataCallback, totalMotionSensor, INTERVAL);
        }


        // 角加速度
        gyroMotionSensor = categoryMotionAgent.getSingleSensor(
                CategoryMotion.SENSOR_TYPE_GYROSCOPE);
        if (gyroMotionSensor != null) {
            categoryMotionAgent.setSensorDataCallback(
                    gyroDataCallback, gyroMotionSensor, INTERVAL);
        }
    }

    //Classification & Showing its label
    public void performClassification() {
        int res = classifier.getResult(accelMeasurements, gyroMeasurements);
        TaskDispatcher uiTaskDispatcher = this.getContext().getUITaskDispatcher();
        String lab = classes[res];
        result = lab;
        TaskDispatcher globalTaskDispatcher = getContext().getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                //打印响应的数据
                HiLog.warn(label, udpClient.sendAndReceive("192.168.0.102", 8800, result));
            }
        });
        uiTaskDispatcher.syncDispatch(new Runnable() {
            @Override
            public void run() {
                Text text = (Text)findComponentById(ResourceTable.Id_text_helloworld);
                text.setText(lab);

                Image image = (Image)findComponentById(ResourceTable.Id_image);

                ResourceManager resourceManager = getResourceManager();

                Resource resource;
                byte[] bytes = null;
                try {
                    resource = null;
                    switch(res) {
                        case 0: resource = resourceManager.getResource(ResourceTable.Media_RESTING); break;
                        case 1: resource = resourceManager.getResource(ResourceTable.Media_STANDING); break;
                        case 2: resource = resourceManager.getResource(ResourceTable.Media_WALKING); break;
                        case 3: resource = resourceManager.getResource(ResourceTable.Media_FALLING); break;
                        case 4: resource = resourceManager.getResource(ResourceTable.Media_WALKING_UPSTAIRS); break;
                        case 5: resource = resourceManager.getResource(ResourceTable.Media_WALKING_DOWNSTAIRS); break;
                        case 6: resource = resourceManager.getResource(ResourceTable.Media_STANDING_UP); break;
                        case 7: resource = resourceManager.getResource(ResourceTable.Media_SITTING); break;
                    }


                    bytes = new byte[resource.available()];

                    //将 Resource 文件数据读入数组中
                    resource.read(bytes);
                } catch (IOException | NotExistException e) {
                    e.printStackTrace();
                }

                // 用于 ImageSource的 create(bytes,srcOpts)方法
                ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
                //设置图片原格式也可以用 null
                srcOpts.formatHint="image/jpg";

                ImageSource imageSource = ImageSource.create(bytes,srcOpts);

                //通过ImageSource创建 PixelMap文件
                PixelMap pixelMap = imageSource.createPixelmap(null);

                //为Image 设置 PixelMap，显示图片
                image.setPixelMap(pixelMap);
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

}


